package com.nextbusmn.server.JDOWrappers;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.nextbusmn.server.dataobjects.CalendarDateData;
import com.nextbusmn.server.dataobjects.NextBusData;

public class CalendarDateJDOWrapper extends JDOWrapper {

	public CalendarDateJDOWrapper(CalendarDateData data) {
		this.setData(data);
	}
	
	@Override
	public boolean dataExists(NextBusData data) {
		CalendarDateData id = getByServiceIDAndDate(((CalendarDateData) data).getServiceID(),
				((CalendarDateData) data).getDate());
		return id != null;
	}
	
	public static CalendarDateData getByServiceIDAndDate(String id, Date date) {
		PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
		
		Query query = pm.newQuery(CalendarDateData.class);
		query.setFilter("serviceID == IDParam && date == dateParam");
		query.declareParameters("String IDParam, java.util.Date dateParam");

		List<CalendarDateData> result = null;
		
		try {
			result = (List<CalendarDateData>) query.execute(id, date);
		} finally {
			query.closeAll();
		}
		
		if (result.size() > 1) {
			System.out.println("Data problem: Key not unique!"); 
		}
		
		return result.size() == 1 ? result.get(0) : null;
	}
	
	public static List<CalendarDateData> getAllRows() {
		return (List<CalendarDateData>) JDOWrapper.getAllRows(CalendarDateData.class);
	}
}
